﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTO;
using System.IO;
using BUS;
using System.Xml;
using System.Data.SqlClient;
using DevExpress.XtraEditors.Controls;

namespace GPBenhLanh
{
    public partial class frmKetQuaGPB : DevExpress.XtraEditors.XtraForm
    {
        public frmKetQuaGPB()
        {
            InitializeComponent();
            initControl(this);
            ByTB = 1;
        }
        TTXacNhanDTO _xn;
        public TTXacNhanDTO Xn
        {
            get { return _xn; }
            set { _xn = value; }
        }

        private TTKetQuaDTO kq = new TTKetQuaDTO();

        string _sThuMucLuu;
        public string sThuMucLuu
        {
            get { return _sThuMucLuu; }
            set { _sThuMucLuu = value; }
        }

        public frmKetQuaGPB(TTXacNhanDTO xnf)
        {
            InitializeComponent();
            Xn = xnf;
            initControl(this);
        }

        //1: nhập kết quả theo số tiêu bản
        //0: nhâp kết quả theo cách truyền thống
        private int ByTB = 0;

        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        private int ketqua = 0;
        private int flagLuu = 1;
        private int flagKQ = 0;
        private int lan = 0;
        public int isCL = 0;
        private DateTime cDate = DateTime.Today;//ngay xac nha cua ket qua
  
        private int[] dataTran = new int[4];//dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
        private static string strPathHinh = "";
        public static string _strConnectPM;
        SqlConnection conpm;  

        public void getPathStrHinh()
        {
            string _sConnection = Uit.it_Conn.getConnectString("pathStrHinh");
            strPathHinh = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }
        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPMo()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhMo");
            _strConnectPM = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public void CnPMo()
        {
            if (conpm == null || conpm.State == ConnectionState.Closed)
            {
                getConnectStringPMo();
                conpm = new System.Data.SqlClient.SqlConnection();
                conpm = Uit.it_Conn.getConnect(_strConnectPM);
            }
        }
        public static string _strConnectPK;
        SqlConnection conpk;

        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPK()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhkham");
            _strConnectPK = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public void CnPKham()
        {
            if (conpk == null || conpk.State == ConnectionState.Closed)
            {
                getConnectStringPK();
                conpk = new SqlConnection();
                conpk = Uit.it_Conn.getConnect(_strConnectPK);
            }
        }
        public delegate void MyDelege2(object sender, Object data);
        public event MyDelege2 thoatEven;

        private int[] isImg= new int[4]{0,0,0,0};

        private void initControl(Control ctrl)
        {

            // Bỏ qua điều kiểm trừ khi nó là TextBox.
            if (ctrl.Tag == "text")
            {
                ctrl.Text = "";
            }

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control ctrlChild in ctrl.Controls)
            {
                initControl(ctrlChild);
            }
        }

        private void loadComboBox()
        {
            DataTable dtbs = GetThongTinSearchBUS.SearchDSBacSi();
            comBacSi.Properties.DataSource = dtbs;
            comKTV.Properties.DataSource = GetThongTinSearchBUS.SearchDSKTV();
            //comBacSi.EditValue = 267;
            comKTV.EditValue = 1;

            DataTable dtBSCD = GetThongTinSearchBUS.SearchDSBacSiCD();
            combscd.Properties.DataSource = dtBSCD;
            comPTV.Properties.DataSource = dtBSCD;

            comPPMo.Properties.DataSource = GetThongTinSearchBUS.SearchPPMo();
            comDonVi.Properties.DataSource = GetThongTinSearchBUS.SearchDonVi(conpk);
            //add 25.01.2015
            DataTable dtPPNhuom = new DataTable ();
            dtPPNhuom = GetThongTinSearchBUS.GetDSPPNhuom();
            comPPNhuom.Properties.DataSource = dtPPNhuom;
            comPPNhuom.Properties.DisplayMember = "TenPPNhuom";
            comPPNhuom.Properties.ValueMember = "IDPPNhuom";
            // Specify the separator character.
            comPPNhuom.Properties.SeparatorChar = ';';
            //setdefaut value pp Nhuom is H&E
            comPPNhuom.SetEditValue(1);
            // Disable the H&E item.
            comPPNhuom.Properties.Items[0].Enabled = false;
            DataTable dtNgCat = GetThongTinSearchBUS.SearchDSNguoiCatLoc();
            comNguoiCatLoc.Properties.DataSource = dtNgCat;

            datNgayCatLoc.DateTime = DateTime.Now.Date.AddDays(-1);
            datNgayLenLam.DateTime = DateTime.Now.Date;
            //end add            
        }

        private void loadTTHC()
        {
            //set thong tin hanh chinh cua benh nha
            txtHoTen.Text = Xn.HoTen;
            int Tuoi = DateTime.Today.Year - Convert.ToInt32(Xn.NamSinh);
            txtTuoi.Text = Xn.NamSinh.ToString();
            if (Xn.Gioi == true)
                txtGioi.Text = "Nam";
            else
                txtGioi.Text = "Nữ";
            txtSDT.Text = Xn.DienThoai;
            txtSoHS.Text = Xn.SoHS;
            txtSoBN.Text = Xn.SoBN;
            txtDichVu.Text = Xn.TenDVu;
            txtSoNVien.Text = Xn.SoNV;
            txtDVChiDinh.Text = Xn.TenDViChiDinh;
            txtChuanDoan.Text = Xn.ChuanDoan;
            DataTable dtbs = GetThongTinSearchBUS.SearchDSBacSi();
            PPMo.Text = Xn.PPMo.ToString();
            PTVien.Text = Xn.PTVien.ToString();
           
            txtsotieuban.Text = Xn.SoTieuBan;
        }
       
        private void loadKQ()
        {
            //load lai kq
            //lan = 2 la gpb 1 la cat lanh
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,txtsotieuban.Text,2);          
            if (dt.Rows.Count > 0)
            {
                string dait, vt, kl;

                vt = dt.Rows[0]["KQViThe"].ToString();
                if (vt == "NNull")
                    vt = "";
                dait = dt.Rows[0]["KQDaiThe"].ToString();
                if (dait == "NNull")
                    dait = "";
                kl = dt.Rows[0]["KetLuan"].ToString();
                if (kl == "NNull")
                    kl = "";

                comBacSi.EditValue = int.Parse(dt.Rows[0]["IDBacSiTH"].ToString());
               
                //combscd.EditValue = Xn.IDBacSiCD;
                comKTV.EditValue = int.Parse(dt.Rows[0]["IDKTV"].ToString());
                txtsotieuban.Text = dt.Rows[0]["SoTieuBan"].ToString();
                
                pnlKQ.Enabled = false;
                cDate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());
                
                btnLuuKetQua.Enabled = false;

                txtViThe1.Text = vt;                    
                txtDaiThe1.Text = dait; 
                txtKetLuan1.Text = kl;
                
                lan = 1;
                isImg[0] = 1;
                Xn.KQ1 = txtsotieuban.Text;
                //add 23.01.2015
                if (dt.Rows[0]["IDNguoiCat"].ToString() != "")
                    comNguoiCatLoc.EditValue = int.Parse(dt.Rows[0]["IDNguoiCat"].ToString());
                else
                    comNguoiCatLoc.EditValue = 0;

                if (dt.Rows[0]["SoLam"].ToString() != "")
                    txtSlgLam.Text = dt.Rows[0]["SoLam"].ToString();
                else
                    txtSlgLam.Text = "0";

                if (dt.Rows[0]["SoLamHM"].ToString() != "")
                    txtSoLamHM.Text = dt.Rows[0]["SoLamHM"].ToString();
                else
                    txtSoLamHM.Text = "0";

                if (dt.Rows[0]["NgayCat"].ToString() != "")
                    datNgayCatLoc.EditValue = Convert.ToDateTime(dt.Rows[0]["NgayCat"].ToString());
                //else
                //    datNgayCatLoc.DateTime = DateTime.Now.Date.AddDays(-1);

                if (dt.Rows[0]["NgayLenLam"].ToString() != "")
                    datNgayLenLam.EditValue = Convert.ToDateTime(dt.Rows[0]["NgayLenLam"].ToString());
                //else
                //    datNgayLenLam.DateTime = DateTime.Now.Date;

                if (dt.Rows[0]["IDPPNhuom"].ToString() != "")
                    comPPNhuom.SetEditValue(dt.Rows[0]["IDPPNhuom"].ToString());
                else
                    comPPNhuom.SetEditValue(1);

                if (dt.Rows[0]["SlgMauCat"].ToString() != "")
                {
                    txtSlgMauCat.Text = dt.Rows[0]["SlgMauCat"].ToString();
                }
                else
                    txtSlgMauCat.Text = "1";
                //end add
                //control cho truong hop da co ket qua
                btnSuaKQ.Visible = true;
                btnCapnhat.Visible = false;
                pnlKQ.Enabled = false;
                btnSuaKQ.Enabled = true;
                flagLuu = 1;
                flagKQ = 1;              
            }
            else//neu chua co ket qua
            {
                lan = 1;
                txtDaiThe1.Text = "";
                txtViThe1.Text = "";
                txtKetLuan1.Text = "";
                btnLuuKetQua.Enabled = true;
                btnSuaKQ.Enabled = false;
                //control cho truong hop chua co ket qua
                btnSuaKQ.Visible = true;
                btnCapnhat.Visible = false;
                pnlKQ.Enabled = true;
                flagLuu = 0;
                flagKQ = 0;
                txtSlgMauCat.Text = "1";

                if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
                {
                    datNgayCatLoc.DateTime = DateTime.Now.Date.AddDays(-3);
                }
                //else
                //{
                //    datNgayCatLoc.DateTime = DateTime.Now.Date.AddDays(-1);
                //}
                //datNgayLenLam.DateTime = DateTime.Now.Date;
                comPPNhuom.SetEditValue(1);
                //comNguoiCatLoc.EditValue = 0;
                //comKTV.EditValue = 0;
                
                txtSlgLam.Text = "1";
                txtSlgMauCat.Text = "1";
                txtSoLamHM.Text = "0";
                //set so tieu ban Byy-XXXXX
                if(ByTB!=1)
                    txtsotieuban.Text = Xn.SoTieuBan;
            }
           
        }

        private void setDataToForm()
        {
            //load lai thong tin hanh chinh cua benh nhan
            loadTTHC();
            //load lai ket qua cho benh nhan
            loadKQ();           
        }
       
        private void LoadHinh(PictureEdit edit, ref Bitmap bm)
        {
            edit.Image = bm;
        }
        
        string path = "";
        private void LoadLaiHinhKQ(string lanthu, PictureEdit pic1, PictureEdit pic2
                                    , ref Bitmap Hinh1, ref Bitmap Hinh2)
        {
            string pathTemp_x100 = Application.StartupPath + "\\PictureTemp" +
                                   "\\"  + "\\x100_" + lanthu.ToString() + ".jpg";
            //x100
            if (File.Exists(pathTemp_x100))
            {
                if (!File.Exists(sThuMucLuu + "\\x100_" + lanthu.ToString() + ".jpg"))
                {
                    CreateDir();
                    File.Copy(pathTemp_x100, sThuMucLuu + "\\" + "\\x100_" + lanthu.ToString() + ".jpg");
                }
            }
            else
            {
                Hinh1 = null;
                LoadHinh(pic1, ref Hinh1);
            }

            string pathHinhDaLuu_x100 = sThuMucLuu + "\\" + "\\x100_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x100))
            {
                Stream stream = File.Open(pathHinhDaLuu_x100, FileMode.Open,
                                            FileAccess.Read, FileShare.ReadWrite);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close(); 

                Hinh1 = m_Bitmap;
                LoadHinh(pic1, ref Hinh1);
            }
            else
            {
                Hinh1 = null;
                LoadHinh(pic1, ref Hinh1);
            }
            //x400
            string pathTemp_x400 = Application.StartupPath + "\\PictureTemp"
                + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathTemp_x400))
            {
                if (!File.Exists(sThuMucLuu + "\\x400_" + lanthu.ToString() + ".jpg"))
                {
                    CreateDir();
                    File.Copy(pathTemp_x400, sThuMucLuu + "\\x400_" + lanthu.ToString() + ".jpg");
                }               
            }
            else
            {
                Hinh2 = null;
                LoadHinh(pic2, ref Hinh2);
            }

            string pathHinhDaLuu_x400 = sThuMucLuu + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x400))
            {

                Stream stream = File.Open(pathHinhDaLuu_x400, FileMode.Open,
                FileAccess.Read, FileShare.ReadWrite);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh2 = m_Bitmap;

                LoadHinh(pic2, ref Hinh2);
            }
            else
            {
                Hinh2 = null;
                LoadHinh(pic2, ref Hinh2);
            }
        }
        
        private void LoadHinh()
        {
            //load lai hinh kq
            LoadLaiHinhKQ(txtsotieuban.Text, picCL1, picCL2, ref bmHinh1, ref bmHinh2);                    
        }
         
        private void frmKetQua_Load(object sender, EventArgs e)
        {
            try
            {
                getPathStrHinh();
                CnPKham();          
                if (ByTB != 1)
                {
                    setDataToForm();
                    ptnByTB.Visible = false;
                    txtsotieuban.Enabled = false;
                }
                loadComboBox();             
                CreateDir();
                LoadHinh();
                if (txtKetLuan1.Text != "")
                    flagKQ = 1;

                btngo_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }            
        } 

        void frm_thoatEven(object sender, object data)
        {
            LoadHinh();
            isImg = (int[])data;
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmChupHinh frmHinh = new frmChupHinh(txtsotieuban.Text,0);
                frmHinh.sThuMucLuu = this.sThuMucLuu;
                frmHinh.thoatEven += new frmChupHinh.DelegeChupH(frm_thoatEven);
                frmHinh.sophieu = Xn.SoBN;

                frmHinh.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void ClearHinh(ref PictureEdit pic, ref Bitmap hinh)
        {
            if (hinh != null)
            {
                hinh.Dispose();
                hinh = null;
                pic.Image = null;
                pic.Refresh();                
            }            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    DialogResult result = MessageBox.Show("Bạn Chưa lưu kết quả./n" +
                        " Bạn có muốn lưu kết quả không ?", "Thông báo", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        btnLuuKetQua_Click(sender, e);
                    }
                }
                ClearHinh(ref picCL1,ref bmHinh1);
                ClearHinh(ref picCL2, ref bmHinh2);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }          
        }

        private void CreateDir()
        {
            string goc = strPathHinh;
            DateTime dt;
            if(Xn!=null)
                dt = Xn.NgayNhan;
            else
                dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4);
        }

        private void btnLuuKetQua_Click(object sender, EventArgs e)
        {
            try
            {
                CnPMo();
                this.ketqua = 1;
                //kiem tra ket qua truoc khi luu
                //set value ket qua 
                if (comBacSi.EditValue.ToString() == "")
                {
                    MessageBox.Show("Bạn phải chọn bác sĩ thực hiện!", "Thông báo");
                    return;
                }
                kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                if (comKTV.EditValue.ToString() == "")
                {
                    kq.IDKTV = 0;
                    return;
                }
                else
                    kq.IDKTV = int.Parse(comKTV.EditValue.ToString());
                kq.SoBN     = Xn.SoBN;
                kq.CDate    = DateTime.Today;
                kq.SoTBan   = txtsotieuban.Text;
                Boolean rs  = false;
                kq.LoaiKQ   = hensu.GPB;
                kq.KQDaiThe1 = txtDaiThe1.Text;
                kq.KQViThe1 = txtViThe1.Text;
                kq.KetLuan1 = txtKetLuan1.Text;
                kq.UrlHinh1 = path;
                kq.Host     = Uit.it_Computer.ComputerName().ToString();
                kq.UserName = UserDTO.LoginName.ToString();
                kq.Lan = 2;
                kq.GhiChu = txtGhiChu.Text;
                //add 25.01.2015
                kq.SoLam = Convert.ToInt32(txtSlgLam.Text);                
                if (comNguoiCatLoc.EditValue.ToString() == "")
                {
                    kq.IDNguoiCat = 0;
                    return;
                }
                else
                    kq.IDNguoiCat = int.Parse(comNguoiCatLoc.EditValue.ToString());
                
                kq.NgayCat = (DateTime)datNgayCatLoc.EditValue;
                kq.NgayLenLam = (DateTime)datNgayLenLam.EditValue;
                kq.IDPPNhuom = GetStringChecked();
                kq.SoLamHM = int.Parse(txtSoLamHM.Text);
                rs = KQBUS.InsertKetQua(kq);                
                //end add
                if (rs)
                {
                    ////cap nhat tuong trinh
                    //lay du lieu phong mo
                    DataTable dtPM =
                    GetThongTinSearchBUS.SearchTuongTrinh(Xn.SoNV, int.Parse(lblLanMo.Text), conpm);

                    //update data vao
                    if (dtPM.Rows.Count > 0)
                    {
                        string TuongTrinh = "";
                        if (txtKetLuan1.Text == "")
                            TuongTrinh = txtViThe1.Text;
                        else
                            TuongTrinh = txtKetLuan1.Text;
                        String SoPT = txtSoNVien.Text;
                        if (SoPT != "")
                        {
                            int LanMo = int.Parse(dtPM.Rows[0]["lanmo"].ToString());
                            GetThongTinSearchBUS.InsertTuongTrinh(SoPT, LanMo, TuongTrinh, conpm);
                        }
                    }

                    rs = false;
                    DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(Xn.DVuCode);
                    int NhomPL = 0;
                    if (dtPL.Rows.Count > 0)
                        NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
                   
                    if (NhomPL == 1)
                    {                        
                        if (!kq.KQDaiThe1.Equals(""))
                            rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 2);
                    }
                    else
                    {
                        if (!kq.KQDaiThe1.Equals(""))
                            rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 1);

                        KQBUS.UpdateFee(kq.SoBN, txtSoHS.Text, txtSoNVien.Text, true
                                    , int.Parse(lblLoaiBN.Text), lblDVCode.Text, conpk);
                    }
                    if (rs)
                    {
                        dataTran[0] = lan;
                        if (lan >= 1)
                            dataTran[1] = 1;
                    }     
                    btnLuuKetQua.Enabled = false;
                    btnSuaKQ.Enabled = true;
                    pnlKQ.Enabled = false;
                    
                    flagLuu = 1;
                    flagKQ = 1;
                    txtsotieuban.Focus();
                                           
                }
                conpm.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }           
        }

        private void btnInKQ_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    XtraMessageBox.Show("Chưa có kết quả!", "Thông báo");
                }
                else if (flagLuu == 1)
                {
                    //LabelHelper.ShowWait(lbIn, "Đang in");
                    rptPhieuKQ rptKQ = new rptPhieuKQ();
                    SerDataToReport(rptKQ);
                    rptKQ.Print();
                    //this.Close();
                }
                else
                {
                    XtraMessageBox.Show("Chưa lưu kết quả!", "Thông báo");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        public int SerDataToReport(rptPhieuKQ rptKQ)
        {
            DateTime cdate = DateTime.Today;
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,txtsotieuban.Text,2);
            if (dt.Rows.Count > 0)
            {

                rptKQ.txtSoTieuBan.Text = dt.Rows[0]["SoTieuBan"].ToString();
                rptKQ.txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString();
                string dait, kl;
                dait = dt.Rows[0]["KQDaiThe"].ToString();
                if (dait == "NNull")
                    dait = "";

                rptKQ.txtdaithe.Text = dait;
                rptKQ.txtVithe.Text = dt.Rows[0]["KQViThe"].ToString();
                string skl = dt.Rows[0]["KetLuan"].ToString();
                if (skl.Trim().Equals("") || skl.Trim().Equals("NNull"))
                {
                    rptKQ.txtketluan.Text = "";
                    rptKQ.txtketluan2.Text = "";
                    rptKQ.lblketluan.Visible = false;
                }
                else
                {
                    rptKQ.txtketluan.Text = dt.Rows[0]["KetLuan"].ToString();
                    rptKQ.txtketluan2.Text = dt.Rows[0]["KetLuan"].ToString();
                }
                rptKQ.txtDViChiDinh.Text = comDonVi.Text;
                rptKQ.txtnghe.Text = Xn.DienThoai;//lblNghe.Text;
                rptKQ.txtchatBP.Text = lblChatBP.Text;
                //add 25.01.2015
                rptKQ.txtPPNhuom.Text = comPPNhuom.Text;
                rptKQ.txtNguoiCatLoc.Text = comNguoiCatLoc.Text;
                if (dt.Rows[0]["NgayCat"].ToString() != "" && comNguoiCatLoc.Text != "  Bệnh viện khác")
                    rptKQ.txtNgayCat.Text = Convert.ToDateTime(dt.Rows[0]["NgayCat"].ToString()).ToString("dd/MM/yyyy");
                else
                     rptKQ.txtNgayCat.Text ="";

                rptKQ.txtNguoiLamTB.Text = comKTV.Text;
                if (dt.Rows[0]["NgayLenLam"].ToString() != "" && comNguoiCatLoc.Text != "  Bệnh viện khác")
                    rptKQ.txtNgayLam.Text = Convert.ToDateTime(dt.Rows[0]["NgayLenLam"].ToString()).ToString("dd/MM/yyyy");
                else
                    rptKQ.txtNgayLam.Text = "";

                if (dt.Rows[0]["SlgMauCat"].ToString() != "")
                    rptKQ.txtSoMau.Text = dt.Rows[0]["SlgMauCat"].ToString();
                else
                    rptKQ.txtSoMau.Text = "";

                if (dt.Rows[0]["SlgMau"].ToString() != "")
                    rptKQ.txtSLgMauGui.Text = dt.Rows[0]["SlgMau"].ToString();
                else
                    rptKQ.txtSLgMauGui.Text = "";

                if (dt.Rows[0]["SoLamHM"].ToString() != "" && int.Parse(dt.Rows[0]["SoLamHM"].ToString()) != 0)
                    rptKQ.txtGhiChu.Text = dt.Rows[0]["SoLamHM"].ToString() + " tiêu bản HMMD. " + dt.Rows[0]["GhiChu"].ToString();
                else
                    rptKQ.txtGhiChu.Text = "";
                rptKQ.txtSoLam.Text = dt.Rows[0]["SoLam"].ToString();
                if (dt.Rows[0]["UserUpdate"].ToString() != "")
                    rptKQ.txtThuKy.Text = dt.Rows[0]["UserUpdate"].ToString();
                else
                    rptKQ.txtThuKy.Text = dt.Rows[0]["UserName"].ToString();
                //end add
            }
            else
            {
                return 1;
            }
            string url = "";
            string gioi = "";
            if (Xn.Gioi)
                gioi = "Nam";
            else
                gioi = "Nữ";
            
            rptKQ.barSoHS.Text = Xn.SoHS;
            rptKQ.txtSoBN.Text = Xn.SoBN;
            rptKQ.txthoten.Text = Xn.HoTen.ToUpper();
            rptKQ.txtGioiTinh.Text = gioi;
            rptKQ.txttuoi.Text =  Xn.NamSinh.ToString()
                                +"("+Xn.Tuoi.ToString()+" Tuổi)";
            rptKQ.txtchuandoan.Text = Xn.ChuanDoan;
            rptKQ.txtngaylaymau.Text = Xn.NgayLayMau.ToString("dd/MM/yyyy");
            rptKQ.txtptv.Text = comPTV.Text;
            rptKQ.txtppmo.Text = comPPMo.Text;//txtPPMo.Text;
            
            rptKQ.txtngaynhanmau.Text = Xn.NgayNhan.ToString("dd/MM/yyyy, hh:mm");

            rptKQ.piclan1.Image = picCL1.Image;
            rptKQ.piclan2.Image = picCL2.Image;
            string dayUpdate = dt.Rows[0]["CDateUpdate"].ToString();
            if (dayUpdate != "")
            {
                cdate = DateTime.Parse(dayUpdate);
            }
            else
            {
                cdate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());
            }
            rptKQ.txttendv.Text = "Đơn vị gửi mẫu";
            rptKQ.txtketqualan.Text = "KẾT QUẢ";
            rptKQ.txtngaythang.Text = "Ngày " + cdate.Day.ToString("00") +
                                  " Tháng " + cdate.Month.ToString("00") +
                                  " Năm " + cdate.Year.ToString("0000");
          
            if (rptKQ.piclan1.Image == null)
            {
                rptKQ.piclan1.Visible = false;
            }
            if (rptKQ.piclan2.Image == null)
            {
                rptKQ.piclan2.Visible = false;
            }
            rptKQ.txtngaygioin.Text = DateTime.Now.ToString("dd/MM/yyyy, hh:mm:ss");
            rptKQ.txtbsthuchien.Text = comBacSi.Text;

            if (txtSoNVien.Text != "")
            {
                string sql = ""
                           + "SELECT                   \n"
                           + "	sonhapvien              \n"
                           + "	,traibenh               \n"
                           + "	,dv.TenDonVi            \n"
                           + "FROM nhapvien            \n"
                           + "INNER JOIN his.dbo.utb_DM_DonVi AS dv ON traibenh = dv.MaDonVi\n"
                           + "WHERE sonhapvien = '" + txtSoNVien.Text + "'\n";
                DataTable dttraiBenh = Uit.it_SQL.getDataTable(sql, conpk);
                if (dttraiBenh != null)
                {
                    rptKQ.txtTraiBenh.Text = dttraiBenh.Rows[0]["TenDonVi"].ToString() + " ";
                }
                else
                {
                    rptKQ.txtTraiBenh.Text = "";
                }
            }
            return 0;
        }

        private void btnPrintRevew_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ != 0 && flagLuu != 0)
                {
                    rptPhieuKQ rptKQ = new rptPhieuKQ();
                    int rs = SerDataToReport(rptKQ);
                    if (rs != 0)
                    {
                        MessageBox.Show("Bạn chưa nhập kết luận!", "Thông Báo");
                        return;
                    }
                    rptKQ.ShowPreviewDialog();
                }
                else
                {
                    DevExpress.LookAndFeel.UserLookAndFeel lookAndFeel = new DevExpress.LookAndFeel.UserLookAndFeel(this);
                    XtraMessageBox.Show(lookAndFeel, "Chưa lưu kết quả.\nBạn phải lưu kết quả trước");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
                //MessageBox.Show("Loi", "Thông Báo");
            }
        }

        private void frmKetQua_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thoatEven != null)
            {
                thoatEven(this, dataTran);
            }
        }

        private void btnSuaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                flagLuu = 0;
             
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
                btnSuaKQ.Visible = false;
                btnCapnhat.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// xoa hinh kho xoa ket qua
        /// </summary>
        /// <param name="kqLan">hinh ket qua lan thu i</param>
        /// <param name="loaiHinh">loai hinh x100 hay x400</param>
        private void xoaHinh(ref PictureEdit picXoa, ref Bitmap hinhXoa
                            , string kqLan, string loaiHinh)
        {
            string urlServer = sThuMucLuu + "\\" + loaiHinh + "_" + kqLan + ".jpg";
            string urlLocal = Application.StartupPath + "\\PictureTemp" +
                                   "\\" + loaiHinh + "_" + kqLan + ".jpg";
            if (File.Exists(urlServer))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa);
                //xoa hinh
                File.Delete(urlServer);
            }
            if (File.Exists(urlLocal))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa);
                //xoa hinh
                File.Delete(urlLocal);
            }           
        }

        private void btnXoaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                //xoa database
                bool rs = KQBUS.DeleteKQ(txtSoBN.Text,txtsotieuban.Text);

                if (rs)
                {
                    //xoa hinh
                    //xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text.Trim(), "X100");
                    //xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text.Trim(), "X400");
                  
                    //update xac nhan
                    bool kqup = false;
                    DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(Xn.DVuCode);
                    int NhomPL = 0;
                    if (dtPL.Rows.Count > 0)
                        NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
                    //if (Xn.DVuCode.Trim() == "GE56")
                    if (NhomPL==1)
                    {
                        kqup = KQBUS.UpdateXacNhan(Xn.SoBN, "0", 2);
                    }
                    else//cat lanh
                    {
                        kqup = KQBUS.UpdateXacNhan(Xn.SoBN, "0", 1);
                    }
                    if (kqup)
                    {
                        //dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
                        dataTran[0] = 0;
                        dataTran[1] = 1;
                        flagLuu = 0;
                        flagKQ = 0;
                        btngo_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(),"Thông Báo");
            }           
        }

        private void btnCapnhat_Click(object sender, EventArgs e)
        {
            try
            {
                CnPMo();
                kq.SoBN = Xn.SoBN;
                kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                kq.CDate = DateTime.Today;

                Boolean rs = false;                  
                kq.KQDaiThe2 = txtDaiThe1.Text;
                kq.KQViThe2 = txtViThe1.Text;
                kq.KetLuan2 = txtKetLuan1.Text;
                kq.SoTBan = txtsotieuban.Text;
                kq.Host = Uit.it_Computer.ComputerName().ToString();
                kq.UserName = UserDTO.LoginName.ToString();
                kq.CDate = DateTime.Now;
                kq.Lan = 2;
                kq.UrlHinh2 = path;
                kq.GhiChu = txtGhiChu.Text;
                // add 23.01.2015
                kq.SoLam = Convert.ToInt32(txtSlgLam.Text);
                kq.SoMauCat = Convert.ToInt32(txtSlgMauCat.Text);
                if (comNguoiCatLoc.EditValue.ToString() == "")
                {
                    kq.IDNguoiCat = 0;
                    return;
                }
                else
                    kq.IDNguoiCat = int.Parse(comNguoiCatLoc.EditValue.ToString());

                kq.NgayCat = (DateTime)datNgayCatLoc.EditValue;
                kq.NgayLenLam = (DateTime)datNgayLenLam.EditValue;
                kq.IDPPNhuom = GetStringChecked();
                if (comKTV.EditValue.ToString() == "")
                {
                    kq.IDKTV = 0;
                    return;
                }
                else
                    kq.IDKTV = int.Parse(comKTV.EditValue.ToString());

                kq.SoLamHM = int.Parse(txtSoLamHM.Text);
                kq.SoMauCat = int.Parse(txtSlgMauCat.Text);
                // end add
                rs = KQBUS.UpdateKetQua(kq);                  

                if (rs)
                {
                    ///cap nhat tuong trinh
                    //lay du lieu phong mo
                    DataTable dtPM =
                    GetThongTinSearchBUS.SearchTuongTrinh(Xn.SoNV, int.Parse(lblLanMo.Text), conpm);

                    //update data vao
                    if (dtPM.Rows.Count > 0)
                    {
                        string TuongTrinh = "";
                        if (txtKetLuan1.Text == "")
                            TuongTrinh = txtViThe1.Text;
                        else
                            TuongTrinh = txtKetLuan1.Text;
                        String SoPT = txtSoNVien.Text;
                        if (SoPT != "")
                        {
                            int LanMo = int.Parse(dtPM.Rows[0]["lanmo"].ToString());
                            GetThongTinSearchBUS.UpdateTuongTrinh(SoPT, LanMo, TuongTrinh, conpm);
                        }
                    }
                    
                    rs = false;
                    DataTable dtPL = GetThongTinSearchBUS.SearchPhanLoaiDV(Xn.DVuCode);
                    int NhomPL = 0;
                    if (dtPL.Rows.Count > 0)
                        NhomPL = int.Parse(dtPL.Rows[0]["IDLoai"].ToString());
                   
                    if (NhomPL == 1)
                    {
                        if (!kq.KQDaiThe2.Equals(""))
                            rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 2);
                    }
                    else
                    {
                        if (!kq.KQDaiThe2.Equals(""))
                            rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, 1);
                    }
                    btnSuaKQ.Visible = true;
                    btnCapnhat.Visible = false;
                    pnlKQ.Enabled = false;
                    flagLuu = 1;
                    flagKQ = 1;
                    txtsotieuban.Focus();
                    conpm.Dispose();
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void frmKetQua_KeyUp(object sender, KeyEventArgs e)
        {           
            switch (e.KeyCode)
            {
                case Keys.F2:
                    SendKeys.Send("{TAB}");
                    btnCapnhat_Click(sender, e);
                    break;
                case Keys.F3:
                    if (btnLuuKetQua.Enabled == true)
                    {
                        SendKeys.Send("{TAB}");
                        btnLuuKetQua_Click(sender, e);
                    }
                    break;
                case Keys.F4:
                    if (btnSuaKQ.Enabled == true)
                        btnSuaKQ_Click(sender, e);
                    break;
                case Keys.F9:
                    btnInKQ_Click(sender, e);
                    break;
                case Keys.F10:
                    btnRpt1_Click(sender, e);
                    break;
                case Keys.F12:
                    if (!txtsotieuban.Text.Trim().Equals(""))
                    {
                        btnNext_Click(sender, e);
                        SendKeys.Send("{TAB}");
                    }
                    break;
                case Keys.F11:
                    if (!txtsotieuban.Text.Trim().Equals("") && btnPrevious.Enabled ==true)
                        btnPrevious_Click(sender, e);
                    break;
            }    
        }

        private void btnXoaH1_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text.Trim(), "X100");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void btnXoaH2_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text.Trim(), "X400");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void txtViThe1_Leave(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
            txtViThe1_Validated( sender,  e);
        }

        private void txtViThe1_Enter(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Enter(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Leave(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Leave(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Enter(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        /// <summary>
        /// Lay chuoi tu phai sang theo leng truyen vao
        /// </summary>
        /// <param name="value">chuoi can cat</param>
        /// <param name="length">chieu dai can cat</param>
        /// <returns>chuoi can cat</returns>
        public string Right(string value, int length)
        {
            if (value != "" && value.Length >= length)
                return value.Substring(value.Length - length);
            return "0";
        }
        /// <summary>
        /// hàm lấy chuỗi từ trái sang
        /// </summary>
        /// <param name="value">giá trị của chuỗi cần cắt</param>
        /// <param name="length">chiều dài cảu chuỗi con</param>
        /// <returns>cuỗi cần lấy</returns>
        public string Left(string value, int length)
        {
            if (value != "" && value.Length >= length)
                return value.Substring(0, length);
            return "0";
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            int numCur = 0, numPrev = 0;
            string pre = "";
            if (Left(txtsotieuban.Text, 2) == hensu.TienToCL)
            {
                if (txtsotieuban.Text.ToUpper() == "")
                {
                    return;
                }
                else
                {
                    numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengSoCatLanh));
                }
                if (numCur <= 2)
                    btnPrevious.Enabled = false;
                numPrev = numCur - 1;
                pre = Left(txtsotieuban.Text.ToUpper(), 5);
                txtsotieuban.Text = pre + numPrev.ToString("0000");
            }
            else
            {
                if (txtsotieuban.Text.ToUpper() == "")
                {
                    return;
                }
                else
                {
                    numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
                }
                if (numCur <= 2)
                    btnPrevious.Enabled = false;
                numPrev = numCur - 1;
                pre = Left(txtsotieuban.Text.ToUpper(), 4);
                txtsotieuban.Text = pre + numPrev.ToString("00000");
            }
            btngo_Click(sender, e);     
        }

        private void btngo_Click(object sender, EventArgs e)
        {
            string SoTieuBan = txtsotieuban.Text;
            if (SoTieuBan.Equals(""))
                return;
            Xn = new TTXacNhanDTO();
            DataTable dt = GetThongTinSearchBUS.SearchDaXacNhanBySoTB(SoTieuBan);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    txtSoHS.Text = dt.Rows[0]["SoHS"].ToString();
                    Xn.SoHS = txtSoHS.Text;

                    txtSoBN.Text = dt.Rows[0]["SoBN"].ToString();
                    Xn.SoBN = dt.Rows[0]["SoBN"].ToString();

                    txtSoNVien.Text = dt.Rows[0]["sonhapvien"].ToString();
                    Xn.SoNV = dt.Rows[0]["sonhapvien"].ToString();

                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString();
                    Xn.HoTen = dt.Rows[0]["HoTen"].ToString();

                    txtGioi.Text = dt.Rows[0]["gioi"].ToString();
                    Xn.Gioi = bool.Parse(dt.Rows[0]["GioiTinh"].ToString());

                    txtTuoi.Text = dt.Rows[0]["namsinh"].ToString()
                                 + "(" + dt.Rows[0]["tuoi"].ToString() + " Tuổi)";
                    Xn.NamSinh = int.Parse(dt.Rows[0]["namsinh"].ToString());
                    Xn.Tuoi = int.Parse(dt.Rows[0]["tuoi"].ToString());

                    txtDichVu.Text = dt.Rows[0]["tendvu"].ToString();
                    Xn.TenDVu = dt.Rows[0]["tendvu"].ToString();

                    txtSDT.Text = dt.Rows[0]["DienThoai"].ToString();
                    Xn.DienThoai = txtSDT.Text;

                    Xn.Nghe = dt.Rows[0]["Nghe"].ToString();
                    lblNghe.Text = dt.Rows[0]["Nghe"].ToString();

                    txtDVChiDinh.Text = dt.Rows[0]["tendonvi"].ToString();
                    Xn.TenDViChiDinh = dt.Rows[0]["tendonvi"].ToString();

                    txtChuanDoan.Text = dt.Rows[0]["chandoan"].ToString();
                    Xn.ChuanDoan = dt.Rows[0]["chandoan"].ToString();
                    Xn.SlgMau = 1;
                    if (dt.Rows[0]["SlgMau"].ToString() != "")
                    {
                        Xn.SlgMau = int.Parse(dt.Rows[0]["SlgMau"].ToString());
                    }

                 
                   
                    //txtSlgMau.Text = Xn.SlgMau.ToString();
                    comPPMo.EditValue = dt.Rows[0]["ppmoid"].ToString();
                    combscd.EditValue = dt.Rows[0]["idbscd"].ToString();
                    comPTV.EditValue = dt.Rows[0]["ptvid"].ToString();
                    lblLanMo.Text = dt.Rows[0]["LanMo"].ToString();

                    Xn.NgayLayMau = DateTime.Parse( dt.Rows[0]["ngaylaymau"].ToString());
                    Xn.NgayNhan = DateTime.Parse(dt.Rows[0]["ngaynhan"].ToString());
                    Xn.DVuCode = dt.Rows[0]["dvucode"].ToString();
                    lblChatBP.Text = dt.Rows[0]["ChatBP"].ToString();                    

                    comDonVi.EditValue = dt.Rows[0]["IDDViGuiMau"].ToString();
                    txtSDT.Text = dt.Rows[0]["DienThoai"].ToString();
                    lblNghe.Text = dt.Rows[0]["Nghe"].ToString();
                    CreateDir();
                    flagLuu = 1;
                    flagKQ = 1;
                    lblDVCode.Text = Xn.DVuCode;
                    lblLoaiBN.Text = dt.Rows[0]["LoaiBN"].ToString();
                }
                else
                {
                    initControl(this);
                }
            }
            LoadHinh();
            loadKQ();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            
            int numCur = 0, numNext = 0;
            string pre = "";
            if (Left(txtsotieuban.Text, 2) == hensu.TienToCL)
            {
                if (txtsotieuban.Text.ToUpper() == "")
                {
                    return;
                }
                else
                {
                    numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengSoCatLanh));
                }

                if (numCur >= 1)
                    btnPrevious.Enabled = true;
                numNext = numCur + 1;

                pre = Left(txtsotieuban.Text.ToUpper(), 5);
                txtsotieuban.Text = pre + numNext.ToString("0000");
            }
            else
            {
                if (txtsotieuban.Text.ToUpper() == "")
                {
                    return;
                }
                else
                {
                    numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
                }

                if (numCur >= 1)
                    btnPrevious.Enabled = true;
                numNext = numCur + 1;

                pre = Left(txtsotieuban.Text.ToUpper(), 4);
                txtsotieuban.Text = pre + numNext.ToString("00000");
            }
            btngo_Click(sender, e);           
        }

        private void txtsotieuban_Validated(object sender, EventArgs e)
        {
            btngo_Click(sender, e);
            txtsotieuban.Text = txtsotieuban.Text.ToUpper();
        }

        private void txtsotieuban_Validating(object sender, CancelEventArgs e)
        {
            
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            frmKetQua_Load(sender, e);
        }

        private void txtViThe1_Validated(object sender, EventArgs e)
        {
            string vithe = txtViThe1.Text;
            string[] words = vithe.Split(new string[] { "\r\n\r\n", "KEÁT LUAÄN:" }, StringSplitOptions.None);
            if (words.Length >= 3)
            {
                txtViThe1.Text = words[0];              
                for (int i = 1; i < words.Length; i++)
                {
                    txtKetLuan1.Text = txtKetLuan1.Text + words[i] + "\r\n";
                }
                
            }           
        }

        private void txtDaiThe1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtDaiThe1_Validated(object sender, EventArgs e)
        {
            
        }

        private List<string> GetChecked()
        {
            List<string> check = new List<string>();
            string checkedString = Convert.ToString(comPPNhuom.Properties.GetCheckedItems());
            if ((checkedString.Length > 0))
            {
                check.AddRange(checkedString.Split(new char[] { ';' }));
            }
            return check;
        }

        private string GetStringChecked()
        {            
            string checkedString = Convert.ToString(comPPNhuom.Properties.GetCheckedItems());

            return checkedString;
        }

        private void BindataToReport(rptPhieuKQ rptKQ, DataRow dr)
        {
            string url_1 = "";
            string url_2 = "";
            string gioi = "";
            DateTime cdate = DateTime.Today;
            rptKQ.txtSoTieuBan.Text = dr["SoTieuBan"].ToString();
            rptKQ.txtDiaChi.Text = dr["DiaChi"].ToString();
            string dait, kl;
            dait = dr["KQDaiThe"].ToString();
            if (dait == "NNull")
                dait = "";

            rptKQ.txtdaithe.Text = dait;
            
            string vt = dr["KQViThe"].ToString();
            rptKQ.txtVithe.Text = vt;

            if (vt == "NNull")
            {
                rptKQ.txtVithe.Text = "";
                rptKQ.lblViThe.Visible = false;
            }

            string skl = dr["KetLuan"].ToString();
            if (dait == "NNull")
                skl = "";
            if (skl.Trim().Equals("") || skl.Trim().Equals("NNull"))
            {
                rptKQ.txtketluan.Text = "";
                rptKQ.txtketluan2.Text = "";
                rptKQ.lblketluan.Visible = false;
            }
            else
            {
                rptKQ.txtketluan.Text = dr["KetLuan"].ToString();
                rptKQ.txtketluan2.Text = dr["KetLuan"].ToString();
            }
            rptKQ.txtDViChiDinh.Text = dr["TenDViChiDinh"].ToString();
            rptKQ.txtnghe.Text = dr["DienThoai"].ToString();
            rptKQ.txtchatBP.Text = Uit.it_Font.Vni2Unicode(dr["ChatBP"].ToString(), false);

            if (Convert.ToBoolean(dr["GioiTinh"].ToString()))
                gioi = "Nam";
            else
                gioi = "Nữ";

            rptKQ.barSoHS.Text = dr["SoHS"].ToString();
            rptKQ.txtSoBN.Text = dr["SoBN"].ToString();
            rptKQ.txthoten.Text = dr["HoTen"].ToString();
            rptKQ.txtGioiTinh.Text = gioi;
            rptKQ.txttuoi.Text = dr["NamSinh"].ToString()
                                + "(" + dr["Tuoi"].ToString() + " Tuổi)";
            rptKQ.txtchuandoan.Text = dr["ChuanDoan"].ToString();
            DateTime ngaylm = new DateTime();
            ngaylm = Convert.ToDateTime(dr["NgayLayMau"].ToString());
            rptKQ.txtngaylaymau.Text = ngaylm.ToString("dd/MM/yyyy");
            rptKQ.txtptv.Text = dr["PTVien"].ToString();
            rptKQ.txtppmo.Text = Uit.it_Font.Vni2Unicode(dr["PPMo"], false);

            cdate = DateTime.Parse(dr["CDate"].ToString());
            rptKQ.txttendv.Text = "Đơn vị gửi mẫu:";
            rptKQ.txtketqualan.Text = "KẾT QUẢ";
            rptKQ.txtngaythang.Text = "Ngày " + cdate.Day.ToString("00") +
                                  " Tháng " + cdate.Month.ToString("00") +
                                  " Năm " + cdate.Year.ToString("0000");

            DateTime ngaynhan = new DateTime();
            ngaynhan = Convert.ToDateTime(dr["NgayNhan"].ToString());
            rptKQ.txtngaynhanmau.Text = ngaynhan.ToString("dd/MM/yyyy, hh:mm");

            //PP nhuom
            string idppn = dr["IDPPNhuom"].ToString();
            comPPNhuom.SetEditValue(idppn);
            rptKQ.txtPPNhuom.Text = comPPNhuom.Text;

            if (dr["SlgMau"].ToString() != "")
                rptKQ.txtSoMau.Text = dr["SlgMau"].ToString();
            else
                rptKQ.txtSoMau.Text = "1";
            rptKQ.txtSoLam.Text = dr["SoLam"].ToString();
            rptKQ.txtNguoiCatLoc.Text = dr["HoTenCat"].ToString();
            if(dr["NgayCat"].ToString()!="")
                rptKQ.txtNgayCat.Text = Convert.ToDateTime(dr["NgayCat"]).ToString("dd/MM/yyyy");
            else
                rptKQ.txtNgayCat.Text ="";

            rptKQ.txtNguoiLamTB.Text = dr["HoTenKTV"].ToString();

            if (dr["NgayLenLam"].ToString() != "")
                rptKQ.txtNgayLam.Text = Convert.ToDateTime(dr["NgayLenLam"]).ToString("dd/MM/yyyy");
            else
                rptKQ.txtNgayLam.Text = "";
            
            string STB = dr["SoTieuBan"].ToString();
            url_1 = hensu.url + ngaynhan.Year + "\\"
                        + ngaynhan.Year.ToString().Substring(2, 2) + ngaynhan.Month.ToString("00")
                        + "\\x100_" + STB + ".jpg";

            url_2 = hensu.url + ngaynhan.Year + "\\"
            + ngaynhan.Year.ToString().Substring(2, 2) + ngaynhan.Month.ToString("00")
            + "\\x400_" + STB + ".jpg";

            if (File.Exists(url_1))
                rptKQ.piclan1.Image = new Bitmap(url_1);
            else
                rptKQ.piclan1.Visible = false;

            if (File.Exists(url_2))
                rptKQ.piclan2.Image = new Bitmap(url_2);
            else
                rptKQ.piclan2.Visible = false;

            if (rptKQ.piclan1.Image == null)
            {
                rptKQ.piclan1.Visible = false;
            }
            if (rptKQ.piclan2.Image == null)
            {
                rptKQ.piclan2.Visible = false;
            }
            rptKQ.txtngaygioin.Text = DateTime.Now.ToString("dd/MM/yyyy, hh:mm:ss");
            rptKQ.txtbsthuchien.Text = dr["HoTenBSTH"].ToString();

            if (dr["UserUpdate"].ToString() != "")
                rptKQ.txtThuKy.Text = dr["UserUpdate"].ToString();
            else
                rptKQ.txtThuKy.Text = dr["UserName"].ToString();

            if (dr["SoLamHM"].ToString() != "" && dr["SoLamHM"].ToString() != "0")
                rptKQ.txtGhiChu.Text = dr["SoLamHM"].ToString() + " tiêu bản HMMD";
            else
                rptKQ.txtGhiChu.Text = "";
            if (dr["SlgMauCat"].ToString() != "")
                rptKQ.txtSoMau.Text = dr["SlgMauCat"].ToString();
            else
                rptKQ.txtSoMau.Text = "";

            string SNVien = dr["SoNhapVien"].ToString();
            if (SNVien != "")
            {
                string sql = ""
                                   + "SELECT                   \n"
                                   + "	sonhapvien              \n"
                                   + "	,traibenh               \n"
                                   + "	,dv.TenDonVi            \n"
                                   + "FROM nhapvien            \n"
                                   + "INNER JOIN his.dbo.utb_DM_DonVi AS dv ON traibenh = dv.MaDonVi\n"
                                   + "WHERE sonhapvien = '" + SNVien + "'\n";
                DataTable dttraiBenh = Uit.it_SQL.getDataTable(sql, conpk);
                if (dttraiBenh != null)
                {
                    rptKQ.txtTraiBenh.Text = dttraiBenh.Rows[0]["TenDonVi"].ToString() + " ";
                }
                else
                {
                    rptKQ.txtTraiBenh.Text = "";
                }
            }
        }
        public int SerDataToReport_History_GPB(rptPhieuKQ rptKQ, string SHS, int lan)
        {
            DateTime cdate = DateTime.Today;
            DataTable dt = KQBUS.GetKetQua(lan, SHS);
            DataRow dr = dt.NewRow();                  

            if (dt.Rows.Count > 0)
            {
                dr = dt.Rows[0];
                BindataToReport(rptKQ, dr);
                rptKQ.CreateDocument();
                for (int i = 1; i <= dt.Rows.Count-1; i++)
                {
                    dr = dt.NewRow();        
                    dr = dt.Rows[i];
                    rptPhieuKQ rptKQ2 = new rptPhieuKQ();
                   
                    BindataToReport(rptKQ2,dr);
                    rptKQ2.CreateDocument();
                    // Add all pages of the 2nd report to the end of the 1st report.
                    rptKQ.Pages.AddRange(rptKQ2.Pages);

                }
            }
            else
            {
                return 1;
            }

            return 0;
        }
        
        private void btnRpt1_Click(object sender, EventArgs e)
        {
            try
            {
                // Create the 1st report and generate its document.
                rptPhieuKQ report1 = new rptPhieuKQ();
                report1.CreateDocument();

                //// Create the 2nd report and generate its document.
                //rptPhieuKQ report2 = new rptPhieuKQ();
                //report2.CreateDocument();

                //// Add all pages of the 2nd report to the end of the 1st report.
                //report1.Pages.AddRange(report2.Pages);

                string soHoSo = txtSoHS.Text;
                int lan = 2;
                SerDataToReport_History_GPB(report1, soHoSo, lan);
                // Reset all page numbers in the resulting document.
                report1.PrintingSystem.ContinuousPageNumbering = true;

                // Show the Print Preview form.
                report1.ShowPreviewDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void lblLanMo_Click(object sender, EventArgs e)
        {
            
        }

        private void txtsotieuban_Leave(object sender, EventArgs e)
        {
            string SoTB = txtsotieuban.Text;
            string MaHieu = Left(SoTB, 1);
            if (MaHieu.ToUpper() != hensu.TienToGPB && MaHieu.ToUpper() != "F")
            {
                MessageBox.Show("Bạn phải nhập số tiêu bản của GPB!", "Thông báo");
                txtsotieuban.Text = "B";
                return;
            }
        }

        private void btnInHangLoat_Click(object sender, EventArgs e)
        {

        }
    }
}